<template>
  <div>
    <div class="search">
      <input v-model="keyWords" class="search-input" type="text" placeholder="输入城市名或拼音">  
    </div>
    <div class="search-content" ref="search" v-show="keyWords">
      <ul>
        <li class="search-item" v-for="item in list" :key="item.id"
        @click="handleCity(item.name)"
        >{{item.name}}</li>
        <li class="search-item" v-show="hasData">没有匹配项</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapState, mapMutations} from 'vuex'
export default {
  name: 'CitySearch',
  props:{
    cities:Object
  },
  methods: {
    handleCity (city) {
      // this.$store.dispatch('changeCity', city)
      // this.$store.commit('changeCity', city)
      this.changeCity(city)
      this.$router.push('/') //编程式导航
    },
    ...mapMutations(['changeCity'])
  },
  data () {
    return {
      list:[],
      keyWords:'',
      timer:null
    }
  },
  computed: {
    hasData () {
      return !this.list.length
    }
  },
  watch: {
    keyWords () {
      if(this.timer){
        clearTimeout(this.timer)
      }
      if(!this.keyWords){
        this.list=[]
        return
      }
      setTimeout(()=>{
        const list = []
        for(let key in this.cities){
          this.cities[key].forEach((value)=>{
            if(value.name.indexOf(this.keyWords)>-1 || value.spell.indexOf(this.keyWords)>-1){
              list.push(value)
            }
          })
        }
        this.list=list
      },200)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl';
.search{
  height: .72rem
  padding: 0 .1rem
  background: $bgColor
  .search-input{
    height:.62rem
    line-height:.62rem
    text-align:center
    border-radius 0.06rem
    width:100%
    color:#666
    box-sizing: border-box
    padding: 0 .1rem
  }
}
.search-content{
  position:absolute
  z-index:3
  top:1.58rem
  right:0
  bottom:0
  left:0
  overflow:hidden
  background:#eee
  .search-item{
    line-height: .62rem
    padding-left: .2rem
    background: #fff
    color: #666
  }
}
</style>
